<template>
  <div class="timeline">
    <div v-for="(item, index) in timeline" :key="index" class="timeline-item">
      <h3 class="timeline-title">{{ item.title }}</h3>
      <el-timeline>
        <el-timeline-item v-for="(it, idx) in item.timelineNode" :key="idx" :timestamp="it.timestamp" placement="top" @click="clickEditNode(index, idx)">
          <div class="timeline-node-content">
            {{ it.content }}
            <el-icon v-if="item.timelineNode.length > 1" @click.stop="clickTimelineItemDelete(index, idx)"><i-ep-Delete /></el-icon>
          </div>
        </el-timeline-item>
      </el-timeline>
      <div class="btn-box">
        <el-button type="primary" @click="clickAddNode(index)">新增节点</el-button>
        <el-button type="danger" @click="clickDeleteTimeline(index)">删除时间线</el-button>
      </div>
    </div>
    <div class="timeline-item">
      <div class="btn-box">
        <el-button type="primary" @click="clickAddTimeline">新增时间线</el-button>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="460px">
      <el-form ref="ruleFormRef" :model="timelineForm" :rules="rules">
        <el-form-item label="标题" prop="title">
          <el-input v-model="timelineForm.title" placeholder="请输入时间线标题" autocomplete="off" maxlength="20" clearable />
        </el-form-item>
        <el-form-item label="时间" prop="timestamp">
          <el-input v-model="timelineForm.timestamp" placeholder="请输入节点时间" autocomplete="off" maxlength="30" clearable />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="timelineForm.content" type="textarea" :rows="4" placeholder="请输入时间节点内容" autocomplete="off" maxlength="1000" resize="none" show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clickCancel(ruleFormRef)">取消</el-button>
          <el-button type="primary" @click="clickConfirm(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
/**
 * 时间线管理页面
 */
import { ref, reactive, onMounted, toRaw, watch, computed } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import "element-plus/es/components/message/style/css";
import "element-plus/es/components/message-box/style/css";
import { useBookStore } from "@/store/modules/bookStore";
const bookStore = useBookStore();

interface TimelineNode {
  id: string;
  timestamp: string;
  content: string;
}
interface Timeline {
  id: string;
  title: string;
  timelineNode: TimelineNode[];
}
// 所有时间线数据
const timeline = ref<Timeline[]>([]);

let bookInfo: any = {};
onMounted(() => {
  // 读取配置文件中的大纲相关数据
  if (bookStore.bookPath) {
    window.electronAPI.readFile(bookStore.bookPath + "/mzBook.json").then((res) => {
      if (res) {
        bookInfo = JSON.parse(res);
        timeline.value = bookInfo.timeline || [];
      }
    });
  }
});

const dialogVisible = ref(false);
// 操作状态：addTimeline, addNode, editNode
const status = ref("addTimeline");
// 当前编辑时间线索引
const timelineIndex = ref(-1);
// 当前编辑时间线节点索引
const timelineNodeIndex = ref(-1);
watch(dialogVisible, (e) => {
  if (!e) {
    timelineIndex.value = -1;
    timelineNodeIndex.value = -1;
    Object.assign(timelineForm, defaultTimelineForm());
    if (ruleFormRef.value) {
      ruleFormRef.value.resetFields();
    }
  }
});
const dialogTitle = computed(() => {
  if (status.value === "addTimeline") {
    return "新增时间线";
  } else if (status.value === "addNode") {
    return "新增时间线节点";
  } else if (status.value === "editNode") {
    return "更新时间线";
  }
});

interface RuleForm {
  id?: string;
  title: string;
  timestamp: string;
  content: string;
}
const ruleFormRef = ref<FormInstance>();
const defaultTimelineForm = () => {
  return {
    title: "",
    timestamp: "",
    content: ""
  };
};
const timelineForm = reactive<RuleForm>(defaultTimelineForm());
// 校验时间线标题
const validateTitle = (rule: any, value: any, callback: any) => {
  // 是否有重名title
  const hasSameTitle = timeline.value.some((ele) => {
    return ele.title === value;
  });
  if (value === "") {
    callback(new Error("请输入时间线标题"));
  } else if (hasSameTitle) {
    callback(new Error("时间线标题不能重复"));
  } else {
    callback();
  }
};
const rules = reactive<FormRules>({
  title: [{ validator: validateTitle, required: true, trigger: "blur" }],
  timestamp: [{ required: true, message: "请输入节点时间", trigger: "blur" }],
  content: [{ required: true, message: "请输入时间节点内容", trigger: "blur" }]
});
// 点击新增时间线
const clickAddTimeline = () => {
  status.value = "addTimeline";
  dialogVisible.value = true;
};
// 点击取消
const clickCancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};
// 新增编辑时间线确认
const clickConfirm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const timelineNode = { id: timelineForm.id ? timelineForm.id : `tln_${new Date().getTime()}`, timestamp: timelineForm.timestamp, content: timelineForm.content };
      if (status.value === "addTimeline") {
        timeline.value.push({
          id: `tl_${new Date().getTime()}`,
          title: timelineForm.title,
          timelineNode: [timelineNode]
        });
      } else if (status.value === "addNode") {
        timeline.value[timelineIndex.value].timelineNode.push(timelineNode);
      } else if (status.value === "editNode") {
        timeline.value[timelineIndex.value].timelineNode[timelineNodeIndex.value] = timelineNode;
      }
      bookInfo = {
        ...bookInfo,
        timeline: toRaw(timeline.value)
      };
      window.electronAPI.writeFile(bookStore.bookPath + "/mzBook.json", JSON.stringify(bookInfo)).then((res) => {
        if (res) {
          dialogVisible.value = false;
          ElMessage({
            message: "操作成功",
            type: "success"
          });
        }
      });
    } else {
      return false;
    }
  });
};
// 点击新增节点
const clickAddNode = (i: number) => {
  status.value = "addNode";
  timelineIndex.value = i;
  timelineForm.title = timeline.value[i].title;
  dialogVisible.value = true;
};
// 点击删除时间线
const clickDeleteTimeline = (i: number) => {
  ElMessageBox.confirm(`确认要删除这条时间线吗?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      timeline.value.splice(i, 1);
      bookInfo = {
        ...bookInfo,
        timeline: toRaw(timeline.value)
      };
      window.electronAPI.writeFile(bookStore.bookPath + "/mzBook.json", JSON.stringify(bookInfo)).then((res) => {
        if (res) {
          ElMessage({
            message: "操作成功",
            type: "success"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
// 点击时间节点，进行编辑
const clickEditNode = (i: number, idx: number) => {
  status.value = "editNode";
  timelineIndex.value = i;
  timelineNodeIndex.value = idx;
  timelineForm.id = timeline.value[i].id;
  timelineForm.title = timeline.value[i].title;
  timelineForm.timestamp = timeline.value[i].timelineNode[idx].timestamp;
  timelineForm.content = timeline.value[i].timelineNode[idx].content;
  dialogVisible.value = true;
};
// 点击时间节点删除
const clickTimelineItemDelete = (i: number, idx: number) => {
  ElMessageBox.confirm(`确认要删除这条时间线节点吗?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      timeline.value[i].timelineNode.splice(idx, 1);
      bookInfo = {
        ...bookInfo,
        timeline: toRaw(timeline.value)
      };
      window.electronAPI.writeFile(bookStore.bookPath + "/mzBook.json", JSON.stringify(bookInfo)).then((res) => {
        if (res) {
          ElMessage({
            message: "操作成功",
            type: "success"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除"
      });
    });
};
</script>

<style lang="scss" scoped>
.timeline {
  height: 100vh;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
  &-item {
    display: inline-block;
    padding: 15px;
    width: 300px;
    height: 100vh;
    box-sizing: border-box;
    border-right: 1px solid var(--el-border-color-lighter);
    overflow: hidden;
    white-space: normal;
    &:last-of-type {
      border-right: none;
    }
    .btn-box {
      text-align: center;
      .el-button {
        width: 200px;
        margin: 0px;
        margin-top: 10px;
      }
    }
    :deep(.el-timeline-item__wrapper):hover {
      .el-icon {
        display: block;
      }
    }
  }
  &-title {
    text-align: center;
    margin-bottom: 15px;
  }
  &-node-content {
    padding: 10px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    box-shadow: var(--el-box-shadow-light);
    cursor: pointer;
    .el-icon {
      display: none;
      position: absolute;
      right: 0px;
      top: 0px;
      font-size: 18px;
    }
  }
}
</style>
